<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\model\Contact as ContactModel;
use app\common\model\User as UserModel;
use app\common\controller\Backend;
use think\Request;

class Contact extends Backend
{
    //留言列表
    public function index()
    {
        $contactList = ContactModel::select()->toArray();
        $userList = UserModel::select()->toArray();
        $userIdMap = array_column($userList, 'username', 'id');
        foreach ($contactList as &$contact) {
            $contact['username'] = '';
            if (!empty($contact['user_id'])) {
                $contact['username'] = $userIdMap[$contact['user_id']];
            }
        }
        return $this->fetch('contact/index', ['contactList' => $contactList]);
    }

    //留言编辑
    public function edit(Request $request)
    {
        $contact = ContactModel::findOrEmpty($request->get('id', 0));
        return $this->fetch('contact/edit', [
            'contact' => $contact
        ]);
    }

    //留言保存
    public function save(Request $request)
    {
        try {
            $data = $request->post();
            if (!empty($data['status'])) {
                $data['status'] = 1;
            } else {
                $data['status'] = 0;
            }
            ContactModel::update($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->redirect('index');
    }

    //留言删除
    public function delete(Request $request)
    {
        try {
            ContactModel::destroy($request->get('id'));
        } catch (\Exception $e) {
            $this->error('删除失败');
        }

        $this->success('删除成功');
    }
}
